#ifndef __BUC_DATAM__
#define __BUC_DATAM__

#include "util.hpp"
#include <unordered_map>
#include <string>
#include <vector>
#include <sstream>

namespace cloud
{
	class DataManage
	{
	private:
		std::string _backup_file; //持久化文件名
		std::unordered_map<std::string, std::string> _table; //内存级数据表  key=文件路径,value=唯一标识

	public:
		DataManage(const std::string& backup_file) :_backup_file(backup_file) 
		{ 
			FileUtil fu(_backup_file);
			if (fu.Exists() == false) fu.SetTruncContent(""); //文件不存在，代替创建文件
			InitLoad(); 
		}

		void InitLoad()
		{
			//读取存入的所有备份数据
			std::string tablestr;
			if (FileUtil(_backup_file).GetContent(&tablestr) == false)
			{
				std::cout << "InitLoad(): Load File Error!" << std::endl;
				return;
			}
			if (tablestr.size() == 0) return;

			//按照规定分割字符串
			int prev = 0;
			size_t pos = tablestr.find('\n', 0);
			while (pos != std::string::npos)
			{
				std::string tmp = tablestr.substr(prev, pos - prev);
				size_t tpos = tmp.find(' ');
				_table[tmp.substr(0, tpos)] = tmp.substr(tpos + 1);
				prev = pos == std::string::npos?prev:pos + 1;
				pos = tablestr.find('\n', prev);
			}
			if (prev != tablestr.size())
			{
				std::string tmp = tablestr.substr(prev);
				size_t tpos = tmp.find(' ');
				_table[tmp.substr(0, tpos)] = tmp.substr(tpos + 1);
			}

		}
		void Storage()
		{
			//组成格式: ("key logo\n")
			std::stringstream ss;
			//遍历备份信息 输入到字符串流
			for (auto& node : _table)
				ss << node.first << " " << node.second << "\n";

			//写入文件
			FileUtil fl(_backup_file);
			fl.SetTruncContent(ss.str());
		}
		bool Insert(const std::string& filename, const std::string& logo) 
		{
			bool ok = _table.emplace(filename, logo).second;
			if(ok) Storage();
			return ok;
		}
		bool Update(const std::string& filename, const std::string& logo) 
		{
			if (_table.count(filename) == 0) return false; //值不存在 则无法更新
			_table[filename] = logo;
			Storage();
			return true;
		}
        //通过文件名获取唯一标识
		bool GetOneByLogo(const std::string& filename, std::string* logo)
		{
			auto target = _table.find(filename);
			if (target == _table.end()) return false;
			*logo = (*target).second;
			return true;
		}
	};
}


#endif // !__BUC_DATAM__

